/**
 * 基于axios对请求接口的配置
 */
import axios from 'axios'
import router from '@/router/index'
axios.defaults.baseURL = "http://localhost:8081";
axios.defaults.withCredentials=true // 允许携带cookie

//请求拦截器
axios.interceptors.request.use((config) => {
  if (window.localStorage.getItem('authToken')) {
    let tokenData = JSON.parse(window.localStorage.getItem('authToken'));
    config.headers.common['authToken'] = tokenData.value;
  }
  //在发送请求之前做些什么
  return config
}, (err) => {
  //对请求错误做些什么
  alert('请求超时')
  return Promise.resolve(err)
})

//http 响应拦截器
axios.interceptors.response.use(response => {
  // 数据统一校验处理
  return response
}, (error) => {
  
  if (error.response) {
    switch (error.response.status) {
      case 401:
        window.localStorage.removeItem('authToken')
        window.localStorage.removeItem('user')
        router.replace({
          path: '/login',
          query: { redirect: router.currentRoute.fullPath } // 将跳转的路由path作为参数，登录成功后跳转到该路由
        })
    }
  }
  return Promise.resolve(err)
})

//登陆请求，需要传一个特殊的请求头
export function loginRequest(url, params) {
  return axios({
    method: 'post',
    url: url,
    data: params,
    headers: {
      'dologin':'true'
    }
  })
}

//get请求
export function getRequest(url,params) {
  return axios({
    method: 'get',
    url:url,
    params:params
  })
}
//post请求
export function postRequest(url, params) {
  return axios({
    method: 'post',
    url: url,
    data: params
  })
}
//上传文件
export function uploadFileRequest(url, params) {
  return axios({
    method: 'post',
    url:url,
    data: params,
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  })
}

export function putRequest(url, params) {
  return axios({
    method: 'put',
    url:url,
    data: params
  })
}

export function deleteRequest(url,params) {
  return axios({
    method: 'delete',
    url: url,
    params:params
  })
}

